/**
 * Created by Yu Jin Xian on 2016/11/25.
 */
var express = require('express');
var handlebars = require('express3-handlebars').create({
    defalutLayout: 'main',
    helpers: {
        section: function (name, options) {
            if (!this.sections) {
                this.sections = {};
            }
            this.sections[name] = options.fn(this);
            return null;
        }
    }
});
var fortune = require('./lib/fortune');

var app = express();

app.set('port', process.env.PORT || 3000);
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');

app.use(express.static(__dirname + '/public'));

app.use(function (req, res, next) {
    res.locals.showTests = app.get('env') != 'production' && req.query.test == '1';
    next();
});

app.get('/', function (req, res) {
    res.render('home');
});

app.get('/about', function (req, res) {
    res.render('about', {
        fortune: fortune.getFortune(),
        pageTestScript: '/qa/tests-about.js'
    });
});

app.get('/tours/hood-river', function (req, res) {
    res.render('tours/hood-river');
});

app.get('/tours/request-group-rate', function (req, res) {
    res.render('tours/request-group-rate');
});

app.get('/newsletter', function (req, res) {
    // 我们会在后面学到 CSRF... 目前, 只提供一个虚拟值
    res.render('newsletter', {csrf: 'CSRF token goes here'});
});

app.post('/process', function (req, res) {
    console.log('Form (from querystring): ' + req.query.form);
    console.log('CSRF token (from hidden form field): ' + req.body._csrf);
    console.log('Name (from visible form field): ' + req.body.name);
    console.log('Email (from visible form field): ' + req.body.email);
    req.redirect(303, '/thank-you');
});

// 定制 404 页面
app.use(function (req, res) {
    res.status(404);
    res.render('404');
});

// 定制 500 页面
app.use(function (err, req, res, next) {
    console.log(err.stack);
    res.status(500);
    res.render('500');
});

app.listen(app.get('port'), function () {
    console.log('Express stated on http://localhost:' + app.get('port') + '; press Ctrl+C to terminate.');
});

